<template>
  <el-dialog
    :visible.sync="isShow"
    :title="mode === 'add' ? '新增部门' : '编辑部门'"
    width="500"
  >
    <el-form label-width="100px" :rules="rules" :model="form" ref="form">
      <el-form-item label="部门名称" prop="name">
        <el-input v-model="form.name"></el-input>
      </el-form-item>
      <el-form-item label="部门编码" prop="code">
        <el-select placeholder="请选择" @focus="focusEvent" v-model="form.code">
          <el-option
            v-for="i in userList"
            :key="i.id"
            :label="i.username"
            :value="i.username"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="部门负责人" prop="manager">
        <el-input v-model="form.manager"></el-input>
      </el-form-item>
      <el-form-item label="部门介绍" prop="introduce">
        <el-input v-model="form.introduce"></el-input>
      </el-form-item>
    </el-form>

    <template #footer>
      <div style="text-align: center">
        <el-button>取消</el-button>
        <el-button type="primary" @click="submit">确定</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script>
import { sysUserSimple } from "@/api/user.js";
import {
  companyDepartmentPost,
  companyDepartmentPut,
} from "@/api/departments.js";
export default {
  name: "DialogItem",
  props: {
    initList: {
      type: Array,
      default: () => [],
    },
  },
  data() {
    return {
      mode: "add",
      bol: true,
      isShow: false,
      userList: [],
      item: "",
      form: {
        name: "",
        code: "",
        manager: "",
        introduce: "",
        pid: "",
      },
      rules: {
        name: [
          { required: true, message: "必填", trigger: "change" },
          {
            validator: (rule, value, callback) => {
              let temp = "";
              // 新增部门
              if (this.mode === "add") {
                // 找出当前部门的所有子部门
                temp = this.initList.filter((item) => {
                  return item.pid === this.item.id;
                });
              }
              // 编辑部门
              else {
                // 找出当前查看部门的兄弟部门
                temp = this.initList.filter((item) => {
                  return item.pid === this.item.pid && item.id !== this.item.id;
                });
              }

              // 判断新增或者修改部门的名称是否出现了重复
              const result = temp.some((item) => {
                return item.name === value.trim();
              });

              result
                ? callback(new Error("请不要输入重复的部门名称" + value))
                : callback();
            },
            trigger: "change",
          },
        ],
        code: [
          { required: true, message: "必填", trigger: "change" },
          {
            validator: (rule, value, callback) => {
              let result = "";
              if (this.mode === "add") {
                result = this.initList.some((item) => {
                  return item.code === value;
                });
              } else {
                result = this.initList.some((item) => {
                  return item.code === value && item.id !== this.item.id;
                });
              }
              result ? callback(new Error("请不要输入重复的code")) : callback();
            },
          },
        ],
        manager: [{ required: true, message: "必填", trigger: "change" }],
        introduce: [{ required: true, message: "必填", trigger: "change" }],
      },
    };
  },
  // 关闭弹框时还原表单数据为初始化
  watch: {
    // 监听 isShow数据的变动
    isShow: {
      handler(newVal) {
        // newVal: 监听到变化的值
        if (!newVal) {
          this.$refs.form.resetFields();
          this.form = {
            name: "",
            code: "",
            manager: "",
            introduce: "",
            pid: "",
          };
        }
      },
    },
  },
  mounted() {
    this.$bus.$on("show", (bol, item, mode = "add") => {
      this.isShow = bol;
      this.item = item;
      this.mode = mode;
      // 深拷贝
      if (mode === "edit") {
        this.form = JSON.parse(JSON.stringify(item));
      }
    });
  },
  beforeDestroy() {
    this.$bus.$off("show");
  },
  methods: {
    async focusEvent() {
      if (this.userList.length === 0) {
        const res = await sysUserSimple();
        this.userList = res.data;
      }
    },
    submit() {
      this.$refs.form.validate(async (result) => {
        if (result) {
          // 新增
          if (this.mode === "add") {
            this.form.pid = this.item.id;
            await companyDepartmentPost(this.form);
          }
          // 编辑
          else {
            await companyDepartmentPut(this.form);
          }
          this.$message.success(this.mode === "add" ? "新增成功" : "编辑成功");
          this.isShow = false;
          this.$emit("getData");
        }
      });
    },
  },
};
</script>

<style></style>
